package a3;

import java.util.Vector;

public class Environment {

	private static Vector<Predator> Predators = new Vector<Predator>();
	private static Prey Prey;
	int BoardSize = 11;
	int MaximumTurns;
	float preyMoveProb = (float) 0.2;
	float alpha, gamma, epsilon, initQ;
	
	
	public Environment(int maxTurns, int boardSize, float Alpha, float Gamma, float Epsilon, float initQ) {
		this.initQ = initQ;
			MaximumTurns = maxTurns;
			BoardSize = boardSize;
			alpha = Alpha;
			gamma = Gamma;
			epsilon = Epsilon;
	}

	public float playGame(Gui gui) {
		int turns = 0;
		int reward = 0;
		boolean finished = false;
		while( !finished )
		{
			moveAgents();
			reward = getRewards();
			turns++;
			if(reward != 0) 
				break;			
			//if(turns > MaximumTurns && MaximumTurns  > 0)
			//	return -1;
			if(gui.Enabled) {
				gui.repaint();
				try {
					Thread.sleep(gui.stoptime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		if(reward<0)
			turns = turns*-1;
			
		return (float)turns;
	}

	private int getRewards() { 
		int reward = 0;
		for( Predator p : Predators ){
			reward += p.getReward();
			//if(reward != 0)
			//System.out.println(reward + " " + p.getReward() +" "+ p.getState().toString());
		}
		return reward/Predators.size();
	}


	public void spawnPredator(Location spawn, String algorithm) {
		Predators.add(new Predator(spawn, this, alpha, gamma, epsilon, algorithm, initQ, Predators.size()));
	}

	public void spawnPrey(Location spawn, String algorithm) {
		Prey = new Prey(spawn, this, alpha, gamma, epsilon, algorithm, initQ, -1);
	}

	public void reset()
	{
		for(int i =0; i < Predators.size(); i++)
		{
			Location newloc;
			switch(i){
				case 0: newloc = new Location(0,0);
					break;
				case 1: newloc = new Location(10,0);
					break;
				case 2: newloc = new Location(0,10);
					break;
				default: newloc = new Location(10,10);
					break;
			}
			Predators.get(i).setLocation(newloc);
		}
		Prey.setLocation(new Location(5,5));
	}

	public void moveAgents() {
		for(Predator p : Predators) {
			p.planAction();
		}
		Prey.planAction();
		
		for(Predator p : Predators) {
			p.takeAction();
		}
		Prey.takeAction();

		for(Predator p : Predators) {
			p.update();
		}
		Prey.update();
	}

	public static Vector<Predator> getPredators() {
		return Predators;
	}

	public static Agent getPrey() {
		return Prey;
	}
}
